package com.atguigu.gmall.common.config.exception;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lfy
 * @Description
 * @create 2023-08-22 11:37
 */
@Component
//@ResponseBody
//@ControllerAdvice //收集所有controller出现的异常
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 统一构造失败响应
     * @param exception
     * @return
     */

    @ExceptionHandler(GmallException.class) //业务期间的所有业务异常都包装为 GmallException 抛出
    public Result handleException(GmallException exception){

        Result<Object> result = new Result<>();
        result.setCode(exception.getCode());
        result.setMessage(exception.getMessage());

        return result;
    }

    /**
     * 处理业务期间的所有异常
     * @param e
     * @return
     */

    @ExceptionHandler(Throwable.class)
    public Result handleException(Throwable e){

        Result<Object> result = new Result<>();

        result.setCode(500);
        result.setMessage(e.getMessage());

        return result;
    }

}
